package com.social.credits.notify;

import com.social.credits.alipay.ScAlipayNotifyService;
import com.social.credits.alipay.ScAlipayService;
import com.social.credits.common.util.ScConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

@RestController
@RequestMapping(value = ScConstant.API_PATH + "/recharge/notify/ali")
public class ScAlipayNotifyController {

    private static final Logger LOGGER = LoggerFactory.getLogger(ScAlipayNotifyController.class);

    @Autowired
    private ScAlipayService scAlipayService;

    @Autowired
    private ScAlipayNotifyService scAlipayNotifyService;

    //回调地址
    @PostMapping
    public void notifyLogic(HttpServletRequest request, HttpServletResponse response) throws IOException {
        LOGGER.info("============ 收到支付宝回调 ==============");

        PrintWriter out = response.getWriter();
        response.setContentType("text/json;charset=utf-8");
        //清空缓存
        response.setDateHeader("expires", 0);
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("pragma", "no-cache");

        //获取支付宝POST过来反馈信息
        Map<String, String[]> requestParams = request.getParameterMap();
        boolean signVerified = scAlipayService.validateSignature(requestParams);

        //商户订单号
        String outTradeNo = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");
        //支付宝交易号
        String tradeNo = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");
        if (signVerified) {//验证成功
            //交易状态
            String tradeStatus = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");
            LOGGER.info("签名验证成功:out_trade_no:{},trade_no:{},trade_status:{}", outTradeNo, tradeNo, tradeStatus);
            // TRADE_SUCCESS 	交易支付成功 此处只有这一种状态会触发通知
//            if (tradeStatus.equals("TRADE_SUCCESS")) {}
            try {
                scAlipayNotifyService.paySuccess(outTradeNo, tradeNo);
            } catch (Exception e) {
                LOGGER.error("支付宝回调,业务处理失败:", e);
                scAlipayNotifyService.payFail(outTradeNo, tradeNo, "支付宝回调,业务处理失败:" + e.getMessage());
            }
            out.println("success");
        } else {//验证失败
            LOGGER.error("支付宝回调,签名失败:{}", outTradeNo);
            scAlipayNotifyService.payFail(outTradeNo, tradeNo, "支付宝回调,签名失败");
            out.println("fail");
        }
    }

}
